import type { Map, MapMouseEvent } from 'mapbox-gl'
import { overlay, symbolProperties } from '@/map'
import { highlightStyle } from '@/map/highlights'
import { IgnoreMouseDrag, isRight, type InteractionTip } from '@/map-interaction'
import { nextName, type AuxPoint, toPoint } from './core'
import { addAuxGraphics } from '../core'

export class AddAuxPoint extends IgnoreMouseDrag {
  public readonly type: string = 'AddAuxPoint'
  public points: Omit<AuxPoint, 'id'>[] = []

  public readonly tip: InteractionTip = {
    title: '绘制辅助点',
    content: '1. 点击地图添加辅助点。\n2. 右键结束绘制。'
  }

  public attach(map: Map): void {
    super.attach(map)

    map.getCanvas().style.cursor = 'crosshair'
    if (this.points.length > 0) {
      this.points = []
    }
  }

  public detach(map: Map): void {
    map.getCanvas().style.cursor = 'auto'
    super.detach(map)
  }

  public onMouseClick(evt: MapMouseEvent): void {
    if (isRight(evt)) {
      addAuxGraphics(this.points)
      this.finish()
      return
    }
    const { lng, lat } = evt.lngLat
    const pt: Omit<AuxPoint, 'id'> = {
      type: 'Point',
      name: nextName(),
      point: { lng, lat }
    }
    overlay.addSymbol({
      type: 'Feature',
      geometry: toPoint(pt),
      properties: symbolProperties(pt.name, highlightStyle.symbol.primary)
    })
    this.points.push(pt)
  }
}
